//
//  Factory.m
//  NLSGProject
//
//  Created by 刘璇 on 2017/5/24.
//  Copyright © 2017年 Xuan. All rights reserved.
//

#import "Factory.h"
#import <CommonCrypto/CommonDigest.h>
#import <sys/utsname.h>
@implementation Factory

+(UIFont *)fitFont:(NSInteger)font
{

    return [UIFont systemFontOfSize:font * kMainSacel];
}
+(UIFont *)fit5Font:(NSInteger)font{
    if (iphone5) {
        return [UIFont systemFontOfSize:font * kMainSacel];
    }
    return [UIFont systemFontOfSize:font];
}
/**
 *  正则表达式验证手机号
 *
 *  @param mobile 传入手机号
 *
 *  @return bool
 */
+ (BOOL)validateMobile:(NSString *)mobile
{
    // 130-139  150-153,155-159  180-189  145,147  170,171,173,176,177,178
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0-9])|(14[57])|(17[013678])|(19[9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
//邮箱地址的正则表达式
+ (BOOL)isValidateEmail:(NSString *)email{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

///手势
+(void)addGestureWithView:(UIView *)anView andSelector:(SEL)selctor{
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:selctor];
    [anView addGestureRecognizer:tap];
}
/**
 
 计算单行文字的size
 
 @parms  文本
 
 @parms  字体
 
 @return  字体的CGSize
 
 */

+ (CGSize)sizeWithText:(NSString *)text withFont:(UIFont *)font{
    
    CGSize size = [text sizeWithAttributes:@{NSFontAttributeName:font}];
    
    return size;
    
}

/**
 
 计算多行文字的CGRect
 
 @parms  文本
 
 @parms  字体
 
 @return  字体的CGRect
 
 */

+ (CGRect)boundingRectWithString:(NSString *)str withSize:(CGSize)size withFont:(UIFont *)font{
    
    CGRect rect = [str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil];
    
    return rect;
    
}

+(CGFloat)getSpaceLabelString:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width space:(NSInteger)space {
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    
    paraStyle.alignment = NSTextAlignmentLeft;
    
    /** 行高 */
    
    paraStyle.lineSpacing = space;
    
    paraStyle.hyphenationFactor = 1.0;
    
    paraStyle.firstLineHeadIndent = 0.0;
    
    paraStyle.paragraphSpacingBefore = 0.0;
    
    paraStyle.headIndent = 0;
    
    paraStyle.tailIndent = 0;
    
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
                          
                          };
    
    CGSize size = [str boundingRectWithSize:CGSizeMake(width,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    
    return size.height;
    
}
+(NSMutableAttributedString *)setLineSpaceAttributedStringWithString:(NSString *)str withLineSpace:(CGFloat)height center:(BOOL)center {
    if (str.length == 0) {
        str = @"";
    }
    
    //设置带有行间距的文本
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:height];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    
    if (center) {
        paragraphStyle.alignment = NSTextAlignmentCenter;
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    }
    
    
    
    return attributedString;
}

+(NSMutableAttributedString *)setLineSpaceAttributedStringWithString:(NSString *)str withLineSpace:(CGFloat)height font:(UIFont *)font{
    if (str.length == 0) {
        str = @"";
    }
    
    //设置带有行间距的文本
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:height];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    
    [attributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [str length])];
    
    return attributedString;
}





+(UIImage *)getPersonHeaderImage{
    NSString * path = [documentPath stringByAppendingPathComponent:@"headerImage.png"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return [UIImage imageWithContentsOfFile:path];
    }else{
        return [UIImage imageNamed:@"头像占位符2.jpg"];
    }
}
+(BOOL)savePersonHeaderImage:(NSString *)headerImage{
    NSString * path = [documentPath stringByAppendingPathComponent:@"headerImage.png"];
    //如果存在  则删除
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]){
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    }
    //保存到沙盒
    if (headerImage.length > 0) {
        NSURL *url = [NSURL URLWithString:headerImage];
        NSLog(@"touxiang:%@",headerImage);
        NSURLSessionDataTask * DataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (!error) {
                [data writeToFile:path atomically:YES];
                NSLog(@"图片保存成功");
            }else{
                NSLog(@"%s:%@",__func__,error.userInfo);
            }
        }];
        [DataTask resume];
    }
    return YES;
}
+(void)deleteHeaderImage{
    NSString * path = [documentPath stringByAppendingPathComponent:@"headerImage.png"];
    //如果存在  则删除
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]){
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    }
}


/**获取当前时间戳*/
+(NSString *)UNIXTime
{
    NSDate* dat = [NSDate date];
    NSTimeInterval a=[dat timeIntervalSince1970] ;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    return timeString;
}
+(NSString *)timeStampFromDate:(NSDate *)date{

    NSTimeInterval  a = [date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f",a * 1000];
    return timeString;
}
/**获取当前时间*/
+(NSString *)CurrentTime
{
    NSDate *date = [NSDate date];
    //2.准备格式对象
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    //3. 设置格式串属性
    formatter.dateFormat = @"yyyy-MM-dd";
   
    //4. 进行格式化(将日期转成字符串)
    return [formatter stringFromDate:date];
}
/**时间戳转化为时间*/
+(NSString *)timeWithTimeIntervalString:(NSString *)timeString withFormat:(NSString *)Format
{
    if (timeString.length < 10 || [timeString isEqualToString:@"0"])
    {
        return @"";
    }
    
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:Format];
    
    NSInteger time = timeString.integerValue;
    
    // 时间戳转时间
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:time];
    NSString *confromTimespStr = [dateformatter stringFromDate:confromTimesp];
    
    return confromTimespStr;
}
/**
 时间转为时间戳
 */
+(NSString *)timeStampFromTime:(NSString *)time withFormat:(NSString *)Format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //指定时间显示样式: HH表示24小时制 hh表示12小时制
    [formatter setDateFormat:Format];

    NSDate *lastDate = [formatter dateFromString:time];
    //以 1970/01/01 GMT为基准，得到lastDate的时间戳
    long firstStamp = [lastDate timeIntervalSince1970] * 1000;
    
    return kStringFromInt(firstStamp);
}

/**获取0点时刻*/
+(NSString *)zeroTimeWithTimestamp:(NSString *)timeStamp{
    NSString * time = [Factory timeWithTimeIntervalString:timeStamp withFormat:@"yyyy-MM-dd"];
    
    return [Factory timeStampFromTime:time withFormat:@"yyyy-MM-dd 00:00:00"];
}

/**
 时间是否是一天的
 */
+(BOOL)judgeEqualDateWithDate1:(NSString *)date1 Date2:(NSString *)date2{
    NSString * time1 = [Factory timeWithTimeIntervalString:date1 withFormat:@"yyyy-MM-dd"];
    NSString * time2 = [Factory timeWithTimeIntervalString:date2 withFormat:@"yyyy-MM-dd"];
    return [time1 isEqualToString:time2];
}
/**
 给数字加单位
 
 @param num <#num description#>
 @return <#return value description#>
 */
+(NSString *)reduceNum:(NSInteger )num{
    if (num > 10000 && num < 100000000) {
        return [NSString stringWithFormat:@"%ld万",(long)num / 10000];
    }else if(num > 100000000){
        return [NSString stringWithFormat:@"%ld亿",(long)num / 100000000];
    }else{
        return kStringFromInt(num);
    }
}



+(void)addNewSceneWithScene:(NSString *)scene{
    if ([scene stringByReplacingOccurrencesOfString:@" " withString:@""].length == 0) {
        
    }
    NSMutableArray * arr = [NSMutableArray new];
    arr = [[[NSUserDefaults standardUserDefaults] objectForKey:@"scene"] mutableCopy];
    if (![arr containsObject:scene]) {
        [arr addObject:scene];
        [[NSUserDefaults standardUserDefaults] setObject:arr forKey:@"scene"];
    }
}


+(NSString * )chineseFromInt:(NSInteger)num{
    
    NSMutableArray * numArr = [NSMutableArray new];
    
    NSInteger result = 1;
    
    do {
        result = num % 10;
        NSNumber * res = [NSNumber numberWithInteger:result];
        [numArr addObject:res];
        
        num = num / 10;
        NSLog(@"%ld",(long)result);
    } while (num > 0);
    
    NSString * chinese = @"";
    for (NSInteger i = (numArr.count -1); i >= 0; i--) {
        NSNumber * res = numArr[i];
        NSInteger result = res.integerValue;
        chinese  = [chinese stringByAppendingString:[self numChineseWithNum:result]];
        chinese  = [chinese stringByAppendingString:[self unitWithNum:result position:i]];
    }
    return chinese;
}
+(NSString *)numChineseWithNum:(NSInteger)num{
    NSArray * arr = @[@"零",@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九"];
    return arr[num];
}
+(NSString *)unitWithNum:(NSInteger)num  position:(NSInteger)position{
    NSArray * arr = @[@"",@"十",@"百",@"千",@"万",@"十",@"百",@"千"];
    if (num == 0) {
        return @"";
    }else{
        return arr[position];
    }
}


// 需要
+ (NSString*)deviceModelName
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([deviceModel isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone3,2"])    return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone3,3"])    return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceModel isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceModel isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPhone5,3"])    return @"iPhone 5c (GSM)";
    if ([deviceModel isEqualToString:@"iPhone5,4"])    return @"iPhone 5c (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPhone6,1"])    return @"iPhone 5s (GSM)";
    if ([deviceModel isEqualToString:@"iPhone6,2"])    return @"iPhone 5s (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceModel isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceModel isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceModel isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([deviceModel isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    // 日行两款手机型号均为日本独占，可能使用索尼FeliCa支付方案而不是苹果支付
    if ([deviceModel isEqualToString:@"iPhone9,1"])    return @"国行、日版、港行iPhone 7";
    if ([deviceModel isEqualToString:@"iPhone9,2"])    return @"港行、国行iPhone 7 Plus";
    if ([deviceModel isEqualToString:@"iPhone9,3"])    return @"美版、台版iPhone 7";
    if ([deviceModel isEqualToString:@"iPhone9,4"])    return @"美版、台版iPhone 7 Plus";
    if ([deviceModel isEqualToString:@"iPhone10,1"])   return @"iPhone_8";
    if ([deviceModel isEqualToString:@"iPhone10,4"])   return @"iPhone_8";
    if ([deviceModel isEqualToString:@"iPhone10,2"])   return @"iPhone_8_Plus";
    if ([deviceModel isEqualToString:@"iPhone10,5"])   return @"iPhone_8_Plus";
    if ([deviceModel isEqualToString:@"iPhone10,3"])   return @"iPhone_X";
    if ([deviceModel isEqualToString:@"iPhone10,6"])   return @"iPhone_X";
    if ([deviceModel isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceModel isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceModel isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceModel isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceModel isEqualToString:@"iPod5,1"])      return @"iPod Touch (5 Gen)";
    if ([deviceModel isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceModel isEqualToString:@"iPad1,2"])      return @"iPad 3G";
    if ([deviceModel isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad2,2"])      return @"iPad 2";
    if ([deviceModel isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([deviceModel isEqualToString:@"iPad2,4"])      return @"iPad 2";
    if ([deviceModel isEqualToString:@"iPad2,5"])      return @"iPad Mini (WiFi)";
    if ([deviceModel isEqualToString:@"iPad2,6"])      return @"iPad Mini";
    if ([deviceModel isEqualToString:@"iPad2,7"])      return @"iPad Mini (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad3,2"])      return @"iPad 3 (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPad3,3"])      return @"iPad 3";
    if ([deviceModel isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad3,5"])      return @"iPad 4";
    if ([deviceModel isEqualToString:@"iPad3,6"])      return @"iPad 4 (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPad4,1"])      return @"iPad Air (WiFi)";
    if ([deviceModel isEqualToString:@"iPad4,2"])      return @"iPad Air (Cellular)";
    if ([deviceModel isEqualToString:@"iPad4,4"])      return @"iPad Mini 2 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad4,5"])      return @"iPad Mini 2 (Cellular)";
    if ([deviceModel isEqualToString:@"iPad4,6"])      return @"iPad Mini 2";
    if ([deviceModel isEqualToString:@"iPad4,7"])      return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad4,8"])      return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad4,9"])      return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad5,1"])      return @"iPad Mini 4 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad5,2"])      return @"iPad Mini 4 (LTE)";
    if ([deviceModel isEqualToString:@"iPad5,3"])      return @"iPad Air 2";
    if ([deviceModel isEqualToString:@"iPad5,4"])      return @"iPad Air 2";
    if ([deviceModel isEqualToString:@"iPad6,3"])      return @"iPad Pro 9.7";
    if ([deviceModel isEqualToString:@"iPad6,4"])      return @"iPad Pro 9.7";
    if ([deviceModel isEqualToString:@"iPad6,7"])      return @"iPad Pro 12.9";
    if ([deviceModel isEqualToString:@"iPad6,8"])      return @"iPad Pro 12.9";
    
    if ([deviceModel isEqualToString:@"AppleTV2,1"])      return @"Apple TV 2";
    if ([deviceModel isEqualToString:@"AppleTV3,1"])      return @"Apple TV 3";
    if ([deviceModel isEqualToString:@"AppleTV3,2"])      return @"Apple TV 3";
    if ([deviceModel isEqualToString:@"AppleTV5,3"])      return @"Apple TV 4";
    
    if ([deviceModel isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceModel isEqualToString:@"x86_64"])       return @"Simulator";
    
    return deviceModel;
}

+(NSString *)MosaicArrayContentWithArray:(NSArray *)array MosaicString:(NSString *)str{
    if (!array.count) {
        return @"";
    }
    __block NSString * result = array[0];
    [array enumerateObjectsUsingBlock:^(NSString *  obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx > 0 && obj.length) {
            result = [result stringByAppendingString:str];
            result = [result stringByAppendingString:obj];
        }
    }];
    
    
    
    result = [result hasPrefix:str] ? [result substringFromIndex:str.length + 1] : result;
    result = [result hasPrefix:str] ? [result substringFromIndex:str.length + 1] : result;
    
    result = [result hasSuffix:str] ? [result substringToIndex:result.length - str.length] : result;
    result = [result hasSuffix:str] ? [result substringToIndex:result.length - str.length] : result;
    
    return result;
}

+(NSString *)removeSpecialCharacterWithString:(NSString *)string character:(NSString *)character{
    while ([string hasPrefix:character]) {
        string = [string substringFromIndex:1];
    }
    
    while ([string hasSuffix:character]) {
        string = [string substringToIndex:string.length-1];
    }
    NSString * str = [NSString stringWithFormat:@"%@%@",character,character];
    while ([string containsString:str]) {
        [string stringByReplacingOccurrencesOfString:str withString:character];
    }
    
    return string;
}
+(NSURL *)imageHolePath:(NSString *)path{
    if (![path hasPrefix:@"http"]) {
        if ([path hasPrefix:@"/"]) {
            path = [path substringFromIndex:1];
        }
        path = [NSString stringWithFormat:@"%@%@",kMainUrlString,path];
    }
    return [NSURL URLWithString:path];
}
+ (BOOL)isIPhoneXAll {
    static BOOL iPhoneXAll = NO;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPhone) {
            if (@available(iOS 11.0, *)) {
                UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
                iPhoneXAll = (window.safeAreaInsets.bottom >= 34 && window.safeAreaInsets.top >= 44);
            }
        }
    });
    
    return iPhoneXAll;
}
@end
